<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>生成指定位数的验证码</title>
</head>

<body>
  <span id="msg"></span>
  <input type="button" onclick="show();" value="刷新">

  <script>
    function validateCode(n) {
      // 随机产生的字符集合
      var a = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      var ret = '';

      // 随机数加结果
      for (let i = 0; i < n; i++) {
        const index = Math.floor(Math.random() * 62);
        ret = ret + a.charAt(index);
      }
      return ret;
    }

    // 显示在页面上
    function show() {
      document.getElementById('msg').innerHTML = validateCode(4);
    }
    // 页面加载时执行函数
    window.onload = show;
  </script>
</body>

</html>